from rest_framework.authentication import BaseAuthentication
from utils.tooljwt import tooljwt
from user import models
import jwt
import datetime
from rest_framework.exceptions import AuthenticationFailed


class Authen(BaseAuthentication):
    def authenticate(self, request):
        # 获取token
        tokendata = request.META.get('HTTP_AUTHORIZATION', None)
        if tokendata:
            # 截取
            token = tokendata.split(' ')[1]
            # 解码 拿到用户id去验证
            try:
                userdata = tooljwt.checktoken(token)
                print(userdata)
                user = models.User.objects.get(id=userdata['userid'])
                print(user)
                # expiration = userdata.get('exp')
                # print(datetime.datetime.fromtimestamp(expiration))
                return user, token
            except jwt.ExpiredSignatureError:
                raise AuthenticationFailed('token过期')
            except jwt.InvalidTokenError:
                raise Exception('token无效')
        else:
            return None, None
